package com.vates.reservas.web;

import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.vates.reservas.dominio.Cliente;
import com.vates.reservas.service.ClienteService;

/**
 * Handles and retrieves the main requests
 */
@Controller
@RequestMapping(value = "/cliente/editar")
public class ClienteEditarController {

	protected static Logger logger = Logger.getLogger("controller");

	@Autowired
	private ClienteService clienteService;

	/**
	 * Handles and retrieves the AJAX Add page
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getClienteEditar(Model model) {
		model.addAttribute(new Cliente());
		return "cliente/editar";
	}

	@RequestMapping(method=RequestMethod.POST)
	public String create(@Valid Cliente cliente, BindingResult result) {
		if (result.hasErrors()) {
			return "cliente/editar";
		}
		return "redirect:/cliente/editar/" + cliente.getId();
	}

	@RequestMapping(value = "{id}", method = RequestMethod.GET)
	public String getClienteModificar(@PathVariable Long id, Model model) {
		model.addAttribute(clienteService.busquedaPorId(id));
		return "cliente/modificar";
	}
	@RequestMapping(method=RequestMethod.POST, value="modificar")
	public String modificar(@Valid Cliente cliente, BindingResult result) {
		if (result.hasErrors()) {
			return "cliente/editar";
		}
		clienteService.editar(cliente.getId(), cliente.getNombre(), cliente.getNif(), cliente.getDomicilio(), cliente.getLocalidad(), cliente.getProvincia(), cliente.getCodigoPostal());
		return "redirect:/cliente/listado/";
	}

}
